import { stringify } from 'querystring';
import { history } from 'umi';
import { getPageQuery, setStore, removeStore } from '@/utils/utils';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';
import { redirectRoute } from '@/utils/authority';
import md5 from 'js-md5';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      let response = yield request(apiPath.ADMIN_LOGIN, {
        method: 'POST',
        data: {
          phone: payload.phone,
          verifi_code: payload.verifi_code,
          password: md5(payload.password)
        },
      });
      if (response.code === 1) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: 'success'
          }
        });
        // 用户信息做本地存储
        setStore({
          name: 'USER_TOKEN',
          content: response.data
        });
        redirectRoute();
      } else {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: 'error'
          }
        });
      }
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note

      // 清除本地存储的用户信息
      removeStore({
        name: 'USER_TOKEN'
      });
      if (window.location.pathname !== '/admin/user/login' && !redirect) {
        history.replace({
          pathname: '/admin/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      return { ...state, status: payload.status };
    },
  },
};
export default Model;
